package com.weixin.engine.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weixin.common.core.doman.Result;
import com.weixin.common.dto.RegionDTO;
import com.weixin.engine.models.pojo.Region;
import com.weixin.engine.models.service.IRegionService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
//import javax.ws.rs.GET;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 前端控制器
 *
 * @author wangchunhui
 * @date 2023-02-16
 */
@RestController
@RequestMapping("/manage/region")
public class RegionController {

    @Resource
    private IRegionService regionService;

    /**
     * 新增Region
     */
    @PostMapping
    public Result add(@RequestBody Region region) {
        boolean flag = regionService.save(region);
        if (!flag) {
            return Result.FAIL();
        }
        return Result.SUCCESS();
    }

    /**
     * 删除Region
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable String id) {
        boolean flag = regionService.removeById(id);
        if (!flag) {
            return Result.FAIL();
        }
        return Result.SUCCESS();
    }

    /**
     * 更新Region
     */
    @PutMapping
    public Result update(@RequestBody Region region) {
        boolean flag = regionService.updateById(region);
        if (!flag) {
            return Result.FAIL();
        }
        return Result.SUCCESS();
    }

    /**
     * Region详情
     */
    @GetMapping("/{id}")
    public Result detail(@PathVariable String id) {
        Region region = regionService.getById(id);
        if (region == null) {
            return Result.FAIL();
        }
        return Result.SUCCESS(region);
    }

    /**
     * Region分页列表
     *
     * @param pageNum  页码
     * @param pageSize 每页记录数
     */
    @PostMapping("/page")
    public Result page(Region region, @RequestParam(defaultValue = "0") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        return Result.SUCCESS();
    }

    @GetMapping("/tree")
    public Result getTree() {
        List<Region> regions = regionService.lambdaQuery().select(Region::getId, Region::getPid, Region::getCode, Region::getName, Region::getLevelId).list();
        List<RegionDTO> regionDTOList = JSONArray.parseArray(JSONObject.toJSONString(regions), RegionDTO.class);
        Map<Long, List<RegionDTO>> perListMap = regionDTOList.stream().collect(Collectors.groupingBy(RegionDTO::getPid));
        regionDTOList.forEach(item -> item.setChildren(perListMap.get(item.getId())));
        regionDTOList = regionDTOList.stream().filter(e -> e.getLevel() == 1).collect(Collectors.toList());
        return Result.SUCCESS(regionDTOList);
    }
}
